<template>
    <section class="content-wrapper">
        <a class="back" href="javascript:void(0)" @click="back"></a>
        <el-row :gutter="20">
            <el-col :span="24" class="cms-form-box">

                <el-row>
                    <el-col>
                        <el-form :inline="false" :model="form" ref="form" :rules="rules" v-loading="loading" label-width="150px">

                            <el-form-item label="素材类型" prop="msgtype">
                                <el-select
                                        clearable
                                        v-model="form.msgtype"
                                        placeholder="请选择"
                                        @change="handleChangeType"
                                        style="width: 400px">
                                    <el-option
                                            v-for="item in messageTypeOptions"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>

                            <el-row :gutter="20" v-if="mpnews">
                                <el-col :span="10">
                                    <el-form-item label="图文消息">
                                        <el-input v-model="form.mpnewsMediaId" placeholder="media_id"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-button type="primary" icon="el-icon-search">选择图文素材</el-button>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20" v-if="text">
                                <el-col :span="10">
                                    <el-form-item label="文本消息">
                                        <el-input
                                                type="textarea"
                                                :autosize="{ minRows: 2, maxRows: 4}"
                                                placeholder="请输入内容"
                                                v-model="form.content">
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20" v-if="voice">
                                <el-col :span="10">
                                    <el-form-item label="语音消息">
                                        <el-input v-model="form.voiceMediaId" placeholder="media_id"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-button type="primary" icon="el-icon-search">选择语音素材</el-button>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20" v-if="image">
                                <el-col :span="10">
                                    <el-form-item label="图片消息">
                                        <el-input v-model="form.imageMediaId" placeholder="media_id"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-button type="primary" icon="el-icon-search">选择图片素材</el-button>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20" v-if="mpvideo">
                                <el-col :span="10">
                                    <el-form-item label="视频消息">
                                        <el-input v-model="form.mpvideoMediaId"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-button type="primary" icon="el-icon-search">选择视频素材</el-button>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20" v-if="wxcard">
                                <el-col :span="10">
                                    <el-form-item label="卡券消息">
                                        <el-input v-model="form.wxcardCardId" placeholder="card_id"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-button type="primary" icon="el-icon-search">选择卡券素材</el-button>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20">
                                <el-col :span="10">
                                    <el-form-item label="群发用户">
                                        <el-button type="primary" size="medium" icon="el-icon-zoom-in" @click="handlerOpenChooseUser">选择用户</el-button>
                                        <el-button v-if="sendToUsers.length > 0" type="primary" size="medium" icon="el-icon-remove-outline" @click="handlerClearAllUser">移除用户</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row :gutter="20" v-if="sendToUsers.length > 0">
                                <el-col :span="10">
                                    <el-form-item label="">
                                        <el-tag
                                                :key="tag.openid"
                                                v-for="tag in sendToUsers"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleClose(tag)"
                                                style="margin-right: 10px;">
                                            {{decodeURI(tag.nickname)}}
                                        </el-tag>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-form-item>
                                <el-button v-if="params.articleId" type="primary" @click="update">编 辑</el-button>
                                <el-button v-else type="primary" @click="send">发 送</el-button>
                                <el-button type="primary" @click="sendPreview">发送预览</el-button>
                                <el-button @click="back">取 消</el-button>
                            </el-form-item>

                        </el-form>
                    </el-col>
                </el-row>

            </el-col>

        </el-row>

        <el-dialog title="用户列表" :visible.sync="dialogFormVisible" @close="handleDialogClose" width="80%">
            <el-table
                    height="400"
                    :data="list"
                    border fit
                    highlight-current-row
                    v-loading="listLoading"
                    element-loading-text="给我一点时间"
                    @selection-change="handleSelectionChange">

                <el-table-column
                        type="selection"
                        width="55" align="center">
                </el-table-column>
                <el-table-column type="index" width="55" align="center"></el-table-column>

                <el-table-column label="头像" width="100px" align="center">
                    <template slot-scope="scope">
                        <img v-if="scope.row.headimgurl" :src="scope.row.headimgurl" alt="" style="width: 46px; height: 46px;">
                    </template>
                </el-table-column>

                <el-table-column label="昵称" width="130px" align="center">
                    <template slot-scope="scope"> {{decodeURI(scope.row.nickname)}} </template>
                </el-table-column>

                <el-table-column label="OPENID" width="300px" align="center">
                    <template slot-scope="scope"> {{scope.row.openid}} </template>
                </el-table-column>

                <el-table-column label="性别" align="center">
                    <template slot-scope="scope">
                        <el-tag type="success" v-if="scope.row.sex === 1">男</el-tag>
                        <el-tag type="danger" v-else>女</el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="国家" align="center">
                    <template slot-scope="scope"> {{scope.row.country}} </template>
                </el-table-column>

                <el-table-column label="省份" align="center">
                    <template slot-scope="scope"> {{scope.row.province}} </template>
                </el-table-column>

                <el-table-column label="城市" align="center">
                    <template slot-scope="scope"> {{scope.row.city}} </template>
                </el-table-column>

                <el-table-column label="关注时间" width="150px" align="center">
                    <template slot-scope="scope"> {{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}} </template>
                </el-table-column>

            </el-table>

            <div v-show="!listLoading" class="pagination-container">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="listQuery.pageNum"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="listQuery.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handlerChooseUser">确 定</el-button>
            </span>
        </el-dialog>

    </section>
</template>

<script>
    import { created, updated, selectTree, getParents, selectOne } from '@/api/weixin/message'
    import { selectList } from '@/api/weixin/subscribeUser'
    import { deleted, deleteByViewUrl, uploadAction } from '@/api/system/oss'

    const messageTypeOptions = [
        {value: 'text', label: '文本'},
        {value: 'mpnews', label: '图文'},
        {value: 'voice', label: '语音'},
        {value: 'image', label: '图片'},
        {value: 'mpvideo', label: '视频'},
        {value: 'wxcard', label: '卡券'}
    ]

    export default {
        name: 'WeixinMessageSendForm',
        data() {
            return {
                /**
                 * articleId
                 */
                params: this.$route.query,
                loading: false,
                messageTypeOptions,
                form: {
                    //填写图文消息的接收者，一串OpenID列表，OpenID最少2个，最多10000个
                    touser: null,
                    //用于设定即将发送的图文消息
                    mpnews: null,
                    //用于群发的图文消息的media_id
                    media_id: null,
                    //群发的消息类型，图文消息为mpnews，文本消息为text，语音为voice，音乐为music，图片为image，视频为video，卡券为wxcard
                    msgtype: null,
                    //视频缩略图的媒体ID
                    thumb_media_id: null,
                    //图文消息被判定为转载时，是否继续群发。 1为继续群发（转载），0为停止群发。 该参数默认为0。
                    send_ignore_reprint: null,
                    //消息的标题
                    title: null,
                    //消息的描述
                    description: null,

                    mpnewsMediaId: null,
                    textMediaId: null,
                    voiceMediaId: null,
                    imageMediaId: null,
                    mpvideoMediaId: null,
                    wxcardCardId: null,

                    sendType: false
                },

                mpnews: false,
                text: false,
                voice: false,
                image: false,
                mpvideo: false,
                wxcard: false,

                rules: {},

                dialogFormVisible: false,
                multipleSelection: [],

                list: [],
                total: null,
                listLoading: false,
                listQuery: {
                    pageNum: 1,
                    pageSize: 10,
                    orderBy: 'ctime desc'
                },
                sendToUsers: []
            }
        },
        created() {
            if(this.params.articleId) {
                selectOne(this.params.articleId).then(response => {
                    this.form = Object.assign({}, response.data)
                })
            }
        },
        methods: {
            back() {
                this.$router.go(-1)
            },
            handleDialogClose() {//关闭窗口回调函数
            },
            handleSelectionChange(val) {//多选
                this.multipleSelection = val;
            },
            handleSelectionChange(val) {//多选
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val
                this.getTableData()
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val
                this.getTableData()
            },
            handlerOpenChooseUser() {
                this.dialogFormVisible =  true
                this.getTableData()
            },
            handlerChooseUser() {
                let selectUsers = this.multipleSelection ;

                if(this.sendToUsers.length == 0) {
                    this.sendToUsers = [...selectUsers]
                } else {
                    //合并两个数组对象
                    this.sendToUsers = [...this.sendToUsers, ...selectUsers]
                }

                var hash = {};
                this.sendToUsers = this.sendToUsers.reduce(function(item, next) {
                    hash[next.openid] ? '' : hash[next.openid] = true && item.push(next);
                    return item
                }, [])

                this.dialogFormVisible =  false
            },
            handleClose(tag) {
                this.sendToUsers.splice(this.sendToUsers.indexOf(tag), 1);
            },
            handlerClearAllUser() {
                this.sendToUsers = []
            },
            getTableData() {
                this.listLoading = true
                selectList(this.listQuery).then(response => {
                    this.list = response.data.list

                    this.total = response.data.total
                    this.listLoading = false
                }).catch(error => {
                    console.log(error)
                    this.listLoading = false
                })
            },

            handleChangeType(value) {
                this.mpnews = false
                this.text = false
                this.voice = false
                this.image = false
                this.mpvideo = false
                this.wxcard = false
                if(value === 'mpnews') {
                    this.mpnews = true
                } else if(value === 'text') {
                    this.text = true
                } else if(value === 'text') {
                    this.text = true
                } else if(value === 'voice') {
                    this.voice = true
                } else if(value === 'image') {
                    this.image = true
                } else if(value === 'mpvideo') {
                    this.mpvideo = true
                } else if(value === 'wxcard') {
                    this.wxcard = true
                }
            },

            send() {//发送
                if(this.sendToUsers.length === 0) {
                    this.$notify({
                        title: '提示', message: '请选择群发用户（至少2位）',
                        type: 'warning', duration: 2000
                    })
                    return
                } else {
                    if(this.sendToUsers.length < 1) {
                        this.$notify({
                            title: '提示', message: '请选择群发用户（至少2位）',
                            type: 'warning', duration: 2000
                        })
                    } else {
                        let userArray = []
                        for(let item of this.sendToUsers) {
                            userArray.push(item.openid)
                        }
                        this.form.touser = userArray.join(',')
                        this.form.sendType = true
                        this.submit()
                    }
                }
            },
            sendPreview() {//发送预览
                if(this.sendToUsers.length === 0) {
                    this.$notify({
                        title: '提示', message: '请选择预览群发用户（1位）',
                        type: 'warning', duration: 2000
                    })
                } else {
                    let userArray = []
                    for(let item of this.sendToUsers) {
                        userArray.push(item.openid)
                    }
                    this.form.touser = userArray.join(',')
                    this.form.sendType = false
                    this.submit()
                }
            },
            submit() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                //this.$router.go(-1)
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })
                    }
                })
            },
            update() {//修改数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        this.form.articleTxt.txt = this.$refs.ue.getUEContent(); // 调用子组件方法

                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.$router.go(-1)
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })
                    }
                })
            },
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>

</style>